<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
  <HEAD>
    <LINK href="default.css" rel="stylesheet" type="text/css">
  </HEAD>
  <BODY><PRE>
<span class="p_commentline"># Copyright (c) 2007, Kundan Singh. All rights reserved. See LICENSING for details.</span>

</PRE><DIV class="commentbox"><b>This file implements RFC4566 (SDP)</b></DIV><PRE>

<span class="p_word">import</span> socket, time

<span class="p_word">class</span> attrs(object):
    <span class="p_triple">'''A generic class that allows uniformly accessing the attribute and items,
    and returns None for invalid attribute instead of throwing an acception.'''</span>
    <span class="p_word">def</span> __init__(self, **kwargs): 
        <span class="p_word">for</span> n,v <span class="p_word">in</span> kwargs.items(): self[n] = v 
    <span class="p_commentline"># attribute access: use container if not found</span>
    <span class="p_word">def</span> __getattr__(self, name): <span class="p_word">return</span> self.__getitem__(name)
    <span class="p_commentline"># container access: use key in __dict__</span>
    <span class="p_word">def</span> __getitem__(self, name): <span class="p_word">return</span> self.__dict__.get(name, <span class="p_word">None</span>)
    <span class="p_word">def</span> __setitem__(self, name, value): self.__dict__[name] = value
    <span class="p_word">def</span> __contains__(self, name): <span class="p_word">return</span> name <span class="p_word">in</span> self.__dict__
    <span class="p_commentline">#def __repr__(self): return repr(self.__dict__)</span>


</PRE><DIV class="commentbox">From RFC4566 p.3<pre>   When initiating multimedia teleconferences, voice-over-IP calls,
   streaming video, or other sessions, there is a requirement to convey
   media details, transport addresses, and other session description
   metadata to the participants.

   SDP provides a standard representation for such information,
   irrespective of how that information is transported.  SDP is purely a
   format for session description -- it does not incorporate a transport
   protocol, and it is intended to use different transport protocols as
   appropriate, including the Session Announcement Protocol [14],
   Session Initiation Protocol [15], Real Time Streaming Protocol [16],
   electronic mail using the MIME extensions, and the Hypertext
   Transport Protocol.

   SDP is intended to be general purpose so that it can be used in a
   wide range of network environments and applications.  However, it is
   not intended to support negotiation of session content or media
   encodings: this is viewed as outside the scope of session
   description.</pre></DIV><PRE>
<span class="p_word">class</span> SDP(attrs):
    <span class="p_triple">'''A SDP packet with dynamic properties. 
    The header names can be accessed as attributes or items. 
    Accessing an unavailable header gives None instead of exception.
    '''</span>

    <span class="p_commentline"># header names that can appear multiple times.</span>
    _multiple = <span class="p_string">'tramb'</span>
    
    <span class="p_word">def</span> __init__(self, value=<span class="p_word">None</span>):
        <span class="p_word">if</span> value: 
            self._parse(value)


</PRE><DIV class="commentbox">From RFC4566 p.11<pre>5.2.  Origin ("o=")

      o=&amp;lt;username&amp;gt; &amp;lt;sess-id&amp;gt; &amp;lt;sess-version&amp;gt; &amp;lt;nettype&amp;gt; &amp;lt;addrtype&amp;gt;
        &amp;lt;unicast-address&amp;gt;

   The "o=" field gives the originator of the session (her username and
   the address of the user's host) plus a session identifier and version
   number:

   &amp;lt;username&amp;gt; is the user's login on the originating host, or it is "-"
      if the originating host does not support the concept of user IDs.
      The &amp;lt;username&amp;gt; MUST NOT contain spaces.

   &amp;lt;sess-id&amp;gt; is a numeric string such that the tuple of &amp;lt;username&amp;gt;,
      &amp;lt;sess-id&amp;gt;, &amp;lt;nettype&amp;gt;, &amp;lt;addrtype&amp;gt;, and &amp;lt;unicast-address&amp;gt; forms a
      globally unique identifier for the session.  The method of
      &amp;lt;sess-id&amp;gt; allocation is up to the creating tool, but it has been
      suggested that a Network Time Protocol (NTP) format timestamp be
      used to ensure uniqueness [13].

   &amp;lt;sess-version&amp;gt; is a version number for this session description.  Its
      usage is up to the creating tool, so long as &amp;lt;sess-version&amp;gt; is
      increased when a modification is made to the session data.  Again,
      it is RECOMMENDED that an NTP format timestamp is used.

   &amp;lt;nettype&amp;gt; is a text string giving the type of network.  Initially
      "IN" is defined to have the meaning "Internet", but other values
      MAY be registered in the future (see Section 8).

   &amp;lt;addrtype&amp;gt; is a text string giving the type of the address that
      follows.  Initially "IP4" and "IP6" are defined, but other values
      MAY be registered in the future (see Section 8).

   &amp;lt;unicast-address&amp;gt; is the address of the machine from which the
      session was created.  For an address type of IP4, this is either
      the fully qualified domain name of the machine or the dotted-
      decimal representation of the IP version 4 address of the machine.
      For an address type of IP6, this is either the fully qualified
      domain name of the machine or the compressed textual
      representation of the IP version 6 address of the machine.  For
      both IP4 and IP6, the fully qualified domain name is the form that
      SHOULD be given unless this is unavailable, in which case the
      globally unique address MAY be substituted.  A local IP address
      MUST NOT be used in any context where the SDP description might
      leave the scope in which the address is meaningful (for example, a
      local address MUST NOT be included in an application-level
      referral that might leave the scope).

   In general, the "o=" field serves as a globally unique identifier for
   this version of this session description, and the subfields excepting
   the version taken together identify the session irrespective of any
   modifications.

   For privacy reasons, it is sometimes desirable to obfuscate the
   username and IP address of the session originator.  If this is a
   concern, an arbitrary &amp;lt;username&amp;gt; and private &amp;lt;unicast-address&amp;gt; MAY be
   chosen to populate the "o=" field, provided that these are selected
   in a manner that does not affect the global uniqueness of the field.</pre></DIV><PRE>
    <span class="p_word">class</span> originator(attrs):
        <span class="p_triple">'''Represents a o= line with attributes username (str), sessionid (long), 
        version (long), nettype (str), addrtype (str), address (str).'''</span>
        <span class="p_word">def</span> __init__(self, value=<span class="p_word">None</span>):
            <span class="p_word">if</span> value:
                self.username, self.sessionid, self.version, self.nettype, self.addrtype, self.address = value.split(<span class="p_string">' '</span>)
                self.sessionid = int(self.sessionid)
                self.version   = int(self.version)
            <span class="p_word">else</span>:
                hostname = socket.gethostname()
                self.username, self.sessionid, self.version, self.nettype, self.addrtype, self.address = \
                <span class="p_string">'-'</span>, int(time.time()), int(time.time()), <span class="p_string">'IN'</span>, <span class="p_string">'IP4'</span>, (hostname.find(<span class="p_string">'.'</span>)&gt;<span class="p_number">0</span> <span class="p_word">and</span> hostname <span class="p_word">or</span> socket.gethostbyname(hostname))
        <span class="p_word">def</span> __repr__(self):
            <span class="p_word">return</span> <span class="p_string">' '</span>.join(map(<span class="p_word">lambda</span> x: str(x), [self.username, self.sessionid, self.version, self.nettype, self.addrtype, self.address]))
        

</PRE><DIV class="commentbox">From RFC4566 p.14<pre>      c=&amp;lt;nettype&amp;gt; &amp;lt;addrtype&amp;gt; &amp;lt;connection-address&amp;gt;

   The "c=" field contains connection data.

   A session description MUST contain either at least one "c=" field in
   each media description or a single "c=" field at the session level.
   It MAY contain a single session-level "c=" field and additional "c="
   field(s) per media description, in which case the per-media values
   override the session-level settings for the respective media.

   The first sub-field ("&amp;lt;nettype&amp;gt;") is the network type, which is a
   text string giving the type of network.  Initially, "IN" is defined
   to have the meaning "Internet", but other values MAY be registered in
   the future (see Section 8).

   The second sub-field ("&amp;lt;addrtype&amp;gt;") is the address type.  This allows
   SDP to be used for sessions that are not IP based.  This memo only
   defines IP4 and IP6, but other values MAY be registered in the future
   (see Section 8).

   The third sub-field ("&amp;lt;connection-address&amp;gt;") is the connection
   address.  OPTIONAL sub-fields MAY be added after the connection
   address depending on the value of the &amp;lt;addrtype&amp;gt; field.

   When the &amp;lt;addrtype&amp;gt; is IP4 and IP6, the connection address is defined
   as follows:

   o  If the session is multicast, the connection address will be an IP
      multicast group address.  If the session is not multicast, then
      the connection address contains the unicast IP address of the
      expected data source or data relay or data sink as determined by
      additional attribute fields.  It is not expected that unicast
      addresses will be given in a session description that is
      communicated by a multicast announcement, though this is not
      prohibited.

   o  Sessions using an IPv4 multicast connection address MUST also have
      a time to live (TTL) value present in addition to the multicast
      address.  The TTL and the address together define the scope with
      which multicast packets sent in this conference will be sent.  TTL
      values MUST be in the range 0-255.  Although the TTL MUST be
      specified, its use to scope multicast traffic is deprecated;
      applications SHOULD use an administratively scoped address
      instead.

   The TTL for the session is appended to the address using a slash as a
   separator.  An example is:

      c=IN IP4 224.2.36.42/127

   IPv6 multicast does not use TTL scoping, and hence the TTL value MUST
   NOT be present for IPv6 multicast.  It is expected that IPv6 scoped
   addresses will be used to limit the scope of conferences.

   Hierarchical or layered encoding schemes are data streams where the
   encoding from a single media source is split into a number of layers.
   The receiver can choose the desired quality (and hence bandwidth) by
   only subscribing to a subset of these layers.  Such layered encodings
   are normally transmitted in multiple multicast groups to allow
   multicast pruning.  This technique keeps unwanted traffic from sites
   only requiring certain levels of the hierarchy.  For applications
   requiring multiple multicast groups, we allow the following notation
   to be used for the connection address:

      &amp;lt;base multicast address&amp;gt;[/&amp;lt;ttl&amp;gt;]/&amp;lt;number of addresses&amp;gt;

   If the number of addresses is not given, it is assumed to be one.
   Multicast addresses so assigned are contiguously allocated above the
   base address, so that, for example:

      c=IN IP4 224.2.1.1/127/3

   would state that addresses 224.2.1.1, 224.2.1.2, and 224.2.1.3 are to
   be used at a TTL of 127.  This is semantically identical to including
   multiple "c=" lines in a media description:

      c=IN IP4 224.2.1.1/127
      c=IN IP4 224.2.1.2/127
      c=IN IP4 224.2.1.3/127

   Similarly, an IPv6 example would be:

      c=IN IP6 FF15::101/3

   which is semantically equivalent to:

      c=IN IP6 FF15::101
      c=IN IP6 FF15::102
      c=IN IP6 FF15::103

   (remembering that the TTL field is not present in IPv6 multicast).

   Multiple addresses or "c=" lines MAY be specified on a per-media
   basis only if they provide multicast addresses for different layers
   in a hierarchical or layered encoding scheme.  They MUST NOT be
   specified for a session-level "c=" field.

   The slash notation for multiple addresses described above MUST NOT be
   used for IP unicast addresses.</pre></DIV><PRE>
    <span class="p_word">class</span> connection(attrs):
        <span class="p_triple">'''Represents a c= line with attributes nettype (str), addrtype (str), address (str)
        and optionally ttl (int) and count (int).'''</span>
        <span class="p_word">def</span> __init__(self, value=<span class="p_word">None</span>, **kwargs):
            <span class="p_word">if</span> value:
                self.nettype, self.addrtype, rest = value.split(<span class="p_string">' '</span>)
                rest = rest.split(<span class="p_string">'/'</span>)
                <span class="p_word">if</span> len(rest) == <span class="p_number">1</span>: self.address = rest[<span class="p_number">0</span>]
                <span class="p_word">elif</span> len(rest) == <span class="p_number">2</span>: self.address, self.ttl = rest[<span class="p_number">0</span>], int(rest[<span class="p_number">1</span>])
                <span class="p_word">else</span>: self.address, self.ttl, self.count = rest[<span class="p_number">0</span>], int(rest[<span class="p_number">1</span>]), int(rest[<span class="p_number">2</span>])
            <span class="p_word">elif</span> <span class="p_string">'address'</span> <span class="p_word">in</span> kwargs:
                self.address = kwargs.get(<span class="p_string">'address'</span>)
                self.nettype = kwargs.get(<span class="p_string">'nettype'</span>, <span class="p_string">'IN'</span>)
                self.addrtype = kwargs.get(<span class="p_string">'addrtype'</span>, <span class="p_string">'IP4'</span>)
                <span class="p_word">if</span> <span class="p_string">'ttl'</span> <span class="p_word">in</span> kwargs: self.ttl = int(kwargs.get(<span class="p_string">'ttl'</span>))
                <span class="p_word">if</span> <span class="p_string">'count'</span> <span class="p_word">in</span> kwargs: self.count = int(kwargs.get(<span class="p_string">'count'</span>))
        <span class="p_word">def</span> __repr__(self):
            <span class="p_word">return</span> self.nettype + <span class="p_string">' '</span> + self.addrtype + <span class="p_string">' '</span> + self.address + (<span class="p_string">'/'</span> + str(self.ttl) <span class="p_word">if</span> self.ttl <span class="p_word">else</span> <span class="p_string">''</span>) + (<span class="p_string">'/'</span> + str(self.count) <span class="p_word">if</span> self.count <span class="p_word">else</span> <span class="p_string">''</span>)


</PRE><DIV class="commentbox">From RFC4566 p.22<pre>      m=&amp;lt;media&amp;gt; &amp;lt;port&amp;gt; &amp;lt;proto&amp;gt; &amp;lt;fmt&amp;gt; ...

   A session description may contain a number of media descriptions.
   Each media description starts with an "m=" field and is terminated by
   either the next "m=" field or by the end of the session description.
   A media field has several sub-fields:

   &amp;lt;media&amp;gt; is the media type.  Currently defined media are "audio",
      "video", "text", "application", and "message", although this list
      may be extended in the future (see Section 8).

   &amp;lt;port&amp;gt; is the transport port to which the media stream is sent.  The
      meaning of the transport port depends on the network being used as
      specified in the relevant "c=" field, and on the transport
      protocol defined in the &amp;lt;proto&amp;gt; sub-field of the media field.
      Other ports used by the media application (such as the RTP Control
      Protocol (RTCP) port [19]) MAY be derived algorithmically from the
      base media port or MAY be specified in a separate attribute (for
      example, "a=rtcp:" as defined in [22]).

      If non-contiguous ports are used or if they don't follow the
      parity rule of even RTP ports and odd RTCP ports, the "a=rtcp:"
      attribute MUST be used.  Applications that are requested to send
      media to a &amp;lt;port&amp;gt; that is odd and where the "a=rtcp:" is present
      MUST NOT subtract 1 from the RTP port: that is, they MUST send the
      RTP to the port indicated in &amp;lt;port&amp;gt; and send the RTCP to the port
      indicated in the "a=rtcp" attribute.

      For applications where hierarchically encoded streams are being
      sent to a unicast address, it may be necessary to specify multiple
      transport ports.  This is done using a similar notation to that
      used for IP multicast addresses in the "c=" field:
         m=&amp;lt;media&amp;gt; &amp;lt;port&amp;gt;/&amp;lt;number of ports&amp;gt; &amp;lt;proto&amp;gt; &amp;lt;fmt&amp;gt; ...

      In such a case, the ports used depend on the transport protocol.
      For RTP, the default is that only the even-numbered ports are used
      for data with the corresponding one-higher odd ports used for the
      RTCP belonging to the RTP session, and the &amp;lt;number of ports&amp;gt;
      denoting the number of RTP sessions.  For example:

         m=video 49170/2 RTP/AVP 31

      would specify that ports 49170 and 49171 form one RTP/RTCP pair
      and 49172 and 49173 form the second RTP/RTCP pair.  RTP/AVP is the
      transport protocol and 31 is the format (see below).  If non-
      contiguous ports are required, they must be signalled using a
      separate attribute (for example, "a=rtcp:" as defined in [22]).

      If multiple addresses are specified in the "c=" field and multiple
      ports are specified in the "m=" field, a one-to-one mapping from
      port to the corresponding address is implied.  For example:

         c=IN IP4 224.2.1.1/127/2
         m=video 49170/2 RTP/AVP 31

      would imply that address 224.2.1.1 is used with ports 49170 and
      49171, and address 224.2.1.2 is used with ports 49172 and 49173.

      The semantics of multiple "m=" lines using the same transport
      address are undefined.  This implies that, unlike limited past
      practice, there is no implicit grouping defined by such means and
      an explicit grouping framework (for example, [18]) should instead
      be used to express the intended semantics.

   &amp;lt;proto&amp;gt; is the transport protocol.  The meaning of the transport
      protocol is dependent on the address type field in the relevant
      "c=" field.  Thus a "c=" field of IP4 indicates that the transport
      protocol runs over IP4.  The following transport protocols are
      defined, but may be extended through registration of new protocols
      with IANA (see Section 8):

      *  udp: denotes an unspecified protocol running over UDP.

      *  RTP/AVP: denotes RTP [19] used under the RTP Profile for Audio
         and Video Conferences with Minimal Control [20] running over
         UDP.

      *  RTP/SAVP: denotes the Secure Real-time Transport Protocol [23]
         running over UDP.

      The main reason to specify the transport protocol in addition to
      the media format is that the same standard media formats may be
      carried over different transport protocols even when the network
      protocol is the same -- a historical example is vat Pulse Code
      Modulation (PCM) audio and RTP PCM audio; another might be TCP/RTP
      PCM audio.  In addition, relays and monitoring tools that are
      transport-protocol-specific but format-independent are possible.

   &amp;lt;fmt&amp;gt; is a media format description.  The fourth and any subsequent
      sub-fields describe the format of the media.  The interpretation
      of the media format depends on the value of the &amp;lt;proto&amp;gt; sub-field.

      If the &amp;lt;proto&amp;gt; sub-field is "RTP/AVP" or "RTP/SAVP" the &amp;lt;fmt&amp;gt;
      sub-fields contain RTP payload type numbers.  When a list of
      payload type numbers is given, this implies that all of these
      payload formats MAY be used in the session, but the first of these
      formats SHOULD be used as the default format for the session.  For
      dynamic payload type assignments the "a=rtpmap:" attribute (see
      Section 6) SHOULD be used to map from an RTP payload type number
      to a media encoding name that identifies the payload format.  The
      "a=fmtp:"  attribute MAY be used to specify format parameters (see
      Section 6).

      If the &amp;lt;proto&amp;gt; sub-field is "udp" the &amp;lt;fmt&amp;gt; sub-fields MUST
      reference a media type describing the format under the "audio",
      "video", "text", "application", or "message" top-level media
      types.  The media type registration SHOULD define the packet
      format for use with UDP transport.

      For media using other transport protocols, the &amp;lt;fmt&amp;gt; field is
      protocol specific.  Rules for interpretation of the &amp;lt;fmt&amp;gt; sub-
      field MUST be defined when registering new protocols (see Section
      8.2.2).</pre></DIV><PRE>
    <span class="p_word">class</span> media(attrs):
        <span class="p_triple">'''Represents a m= line and all subsequent lines until next m= or end.
        It has attributes such as media (str), port (int), proto (str), fmt (list).'''</span> 
        <span class="p_word">def</span> __init__(self, value=<span class="p_word">None</span>, **kwargs):
            <span class="p_word">if</span> value:
                self.media, self.port, self.proto, rest = value.split(<span class="p_string">' '</span>, <span class="p_number">3</span>)
                self.port = int(self.port)
                self.fmt = []
                <span class="p_word">for</span> f <span class="p_word">in</span> rest.split(<span class="p_string">' '</span>):
                    a = attrs(); a.pt = f; self.fmt.append(a)
            <span class="p_word">elif</span> <span class="p_string">'media'</span> <span class="p_word">in</span> kwargs:
                self.media = kwargs.get(<span class="p_string">'media'</span>)
                self.port  = int(kwargs.get(<span class="p_string">'port'</span>, <span class="p_number">0</span>))
                self.proto = kwargs.get(<span class="p_string">'proto'</span>, <span class="p_string">'RTP/AVP'</span>)
                self.fmt   = kwargs.get(<span class="p_string">'fmt'</span>, [])
        <span class="p_word">def</span> __repr__(self):
            result = self.media + <span class="p_string">' '</span> + str(self.port) + <span class="p_string">' '</span> + self.proto + <span class="p_string">' '</span> + <span class="p_string">' '</span>.join(map(<span class="p_word">lambda</span> x: str(x.pt), self.fmt))
            <span class="p_word">for</span> k <span class="p_word">in</span> filter(<span class="p_word">lambda</span> x: x <span class="p_word">in</span> self, <span class="p_string">'icbka'</span>): <span class="p_commentline"># order is important</span>
                <span class="p_word">if</span> k <span class="p_word">not</span> <span class="p_word">in</span> SDP._multiple: <span class="p_commentline"># single header</span>
                    result += <span class="p_string">'\r\n'</span> + k + <span class="p_string">'='</span> + str(self[k])
                <span class="p_word">else</span>:
                    <span class="p_word">for</span> v <span class="p_word">in</span> self[k]:
                        result += <span class="p_string">'\r\n'</span> + k + <span class="p_string">'='</span> + str(v) 
            <span class="p_word">for</span> f <span class="p_word">in</span> self.fmt:
                <span class="p_word">if</span> f.name:
                    result += <span class="p_string">'\r\n'</span> + <span class="p_string">'a=rtpmap:'</span> + str(f.pt) + <span class="p_string">' '</span> + f.name + <span class="p_string">'/'</span> + str(f.rate) + (f.params <span class="p_word">and</span> (<span class="p_string">'/'</span>+f.params) <span class="p_word">or</span> <span class="p_string">''</span>)
            <span class="p_word">return</span> result
    
    

</PRE><DIV class="commentbox">From RFC4566 p.8<pre>   An SDP session description consists of a number of lines of text of
   the form:

      &amp;lt;type&amp;gt;=&amp;lt;value&amp;gt;

   where &amp;lt;type&amp;gt; MUST be exactly one case-significant character and
   &amp;lt;value&amp;gt; is structured text whose format depends on &amp;lt;type&amp;gt;.  In
   general, &amp;lt;value&amp;gt; is either a number of fields delimited by a single
   space character or a free format string, and is case-significant
   unless a specific field defines otherwise.  Whitespace MUST NOT be
   used on either side of the "=" sign.

   An SDP session description consists of a session-level section
   followed by zero or more media-level sections.  The session-level
   part starts with a "v=" line and continues to the first media-level
   section.  Each media-level section starts with an "m=" line and
   continues to the next media-level section or end of the whole session
   description.  In general, session-level values are the default for
   all media unless overridden by an equivalent media-level value.

   Some lines in each description are REQUIRED and some are OPTIONAL,
   but all MUST appear in exactly the order given here (the fixed order
   greatly enhances error detection and allows for a simple parser).
   OPTIONAL items are marked with a "*".








      Session description
         v=  (protocol version)
         o=  (originator and session identifier)
         s=  (session name)
         i=* (session information)
         u=* (URI of description)
         e=* (email address)
         p=* (phone number)
         c=* (connection information -- not required if included in
              all media)
         b=* (zero or more bandwidth information lines)
         One or more time descriptions ("t=" and "r=" lines; see below)
         z=* (time zone adjustments)
         k=* (encryption key)
         a=* (zero or more session attribute lines)
         Zero or more media descriptions

      Time description
         t=  (time the session is active)
         r=* (zero or more repeat times)

      Media description, if present
         m=  (media name and transport address)
         i=* (media title)
         c=* (connection information -- optional if included at
              session level)
         b=* (zero or more bandwidth information lines)
         k=* (encryption key)
         a=* (zero or more media attribute lines)

   The set of type letters is deliberately small and not intended to be
   extensible -- an SDP parser MUST completely ignore any session
   description that contains a type letter that it does not understand.
   The attribute mechanism ("a=" described below) is the primary means
   for extending SDP and tailoring it to particular applications or
   media.  Some attributes (the ones listed in Section 6 of this memo)
   have a defined meaning, but others may be added on an application-,
   media-, or session-specific basis.  An SDP parser MUST ignore any
   attribute it doesn't understand.

   An SDP session description may contain URIs that reference external
   content in the "u=", "k=", and "a=" lines.  These URIs may be
   dereferenced in some cases, making the session description non-self-
   contained.




   The connection ("c=") and attribute ("a=") information in the
   session-level section applies to all the media of that session unless
   overridden by connection information or an attribute of the same name
   in the media description.  For instance, in the example below, each
   media behaves as if it were given a "recvonly" attribute.</pre></DIV><PRE>
    <span class="p_word">def</span> _parse(self, text):
        g = True <span class="p_commentline"># whether we are in global line or per media line?</span>
        <span class="p_word">for</span> line <span class="p_word">in</span> text.replace(<span class="p_string">'\r\n'</span>, <span class="p_string">'\n'</span>).split(<span class="p_string">'\n'</span>):
            k, sep, v = line.partition(<span class="p_string">'='</span>)
        
            <span class="p_word">if</span> k == <span class="p_string">'o'</span>: v = SDP.originator(v)
            <span class="p_word">elif</span> k == <span class="p_string">'c'</span>: v = SDP.connection(v)
            <span class="p_word">elif</span> k == <span class="p_string">'m'</span>: v = SDP.media(v)

            <span class="p_word">if</span> k == <span class="p_string">'m'</span>:   <span class="p_commentline"># new m= line</span>
                <span class="p_word">if</span> <span class="p_word">not</span> self[<span class="p_string">'m'</span>]:
                    self[<span class="p_string">'m'</span>] = []
                self[<span class="p_string">'m'</span>].append(v)
                obj = self[<span class="p_string">'m'</span>][-<span class="p_number">1</span>]
            <span class="p_word">elif</span> self[<span class="p_string">'m'</span>]:  <span class="p_commentline"># not in global</span>
                obj = self[<span class="p_string">'m'</span>][-<span class="p_number">1</span>]

</PRE><DIV class="commentbox">From RFC4566 p.25<pre>      a=rtpmap:&amp;lt;payload type&amp;gt; &amp;lt;encoding name&amp;gt;/&amp;lt;clock rate&amp;gt; [/&amp;lt;encoding
         parameters&amp;gt;]

         This attribute maps from an RTP payload type number (as used in
         an "m=" line) to an encoding name denoting the payload format
         to be used.  It also provides information on the clock rate and
         encoding parameters.  It is a media-level attribute that is not
         dependent on charset.
         Although an RTP profile may make static assignments of payload
         type numbers to payload formats, it is more common for that
         assignment to be done dynamically using "a=rtpmap:" attributes.
         As an example of a static payload type, consider u-law PCM
         coded single-channel audio sampled at 8 kHz.  This is
         completely defined in the RTP Audio/Video profile as payload
         type 0, so there is no need for an "a=rtpmap:" attribute, and
         the media for such a stream sent to UDP port 49232 can be
         specified as:

            m=audio 49232 RTP/AVP 0

         An example of a dynamic payload type is 16-bit linear encoded
         stereo audio sampled at 16 kHz.  If we wish to use the dynamic
         RTP/AVP payload type 98 for this stream, additional information
         is required to decode it:

            m=audio 49232 RTP/AVP 98
            a=rtpmap:98 L16/16000/2

         Up to one rtpmap attribute can be defined for each media format
         specified.  Thus, we might have the following:

            m=audio 49230 RTP/AVP 96 97 98
            a=rtpmap:96 L8/8000
            a=rtpmap:97 L16/8000
            a=rtpmap:98 L16/11025/2

         RTP profiles that specify the use of dynamic payload types MUST
         define the set of valid encoding names and/or a means to
         register encoding names if that profile is to be used with SDP.
         The "RTP/AVP" and "RTP/SAVP" profiles use media subtypes for
         encoding names, under the top-level media type denoted in the
         "m=" line.  In the example above, the media types are
         "audio/l8" and "audio/l16".

         For audio streams, &amp;lt;encoding parameters&amp;gt; indicates the number
         of audio channels.  This parameter is OPTIONAL and may be
         omitted if the number of channels is one, provided that no
         additional parameters are needed.

         For video streams, no encoding parameters are currently
         specified.

         Additional encoding parameters MAY be defined in the future,
         but codec-specific parameters SHOULD NOT be added.  Parameters
         added to an "a=rtpmap:" attribute SHOULD only be those required
         for a session directory to make the choice of appropriate media
         to participate in a session.  Codec-specific parameters should
         be added in other attributes (for example, "a=fmtp:").

         Note: RTP audio formats typically do not include information
         about the number of samples per packet.  If a non-default (as
         defined in the RTP Audio/Video Profile) packetisation is
         required, the "ptime" attribute is used as given above.</pre></DIV><PRE>
                <span class="p_word">if</span> k == <span class="p_string">'a'</span> <span class="p_word">and</span> v.startswith(<span class="p_string">'rtpmap:'</span>):
                    pt, rest = v[<span class="p_number">7</span>:].split(<span class="p_string">' '</span>, <span class="p_number">1</span>)
                    name, sep, rest = rest.partition(<span class="p_string">'/'</span>)
                    rate, sep, params = rest.partition(<span class="p_string">'/'</span>)
                    <span class="p_word">for</span> f <span class="p_word">in</span> filter(<span class="p_word">lambda</span> x: x.pt == pt, obj.fmt):
                        f.name = name; f.rate = int(rate); f.params = params <span class="p_word">or</span> <span class="p_word">None</span>
                <span class="p_word">else</span>:
                    obj[k] = (k <span class="p_word">in</span> SDP._multiple <span class="p_word">and</span> ((k <span class="p_word">in</span> obj) <span class="p_word">and</span> (obj[k]+v) <span class="p_word">or</span> [v])) <span class="p_word">or</span> v 
            <span class="p_word">else</span>:          <span class="p_commentline"># global</span>
                obj = self
                obj[k] = ((k <span class="p_word">in</span> SDP._multiple) <span class="p_word">and</span> ((k <span class="p_word">in</span> obj) <span class="p_word">and</span> (obj[k]+v) <span class="p_word">or</span> [v])) <span class="p_word">or</span> v

    <span class="p_word">def</span> __repr__(self):
        result = <span class="p_string">''</span>
        <span class="p_word">for</span> k <span class="p_word">in</span> filter(<span class="p_word">lambda</span> x: x <span class="p_word">in</span> self, <span class="p_string">'vosiuepcbtam'</span>): <span class="p_commentline"># order is important</span>
            <span class="p_word">if</span> k <span class="p_word">not</span> <span class="p_word">in</span> SDP._multiple: <span class="p_commentline"># single header</span>
                result += k + <span class="p_string">'='</span> + str(self[k]) + <span class="p_string">'\r\n'</span>
            <span class="p_word">else</span>:
                <span class="p_word">for</span> v <span class="p_word">in</span> self[k]:
                    result += k + <span class="p_string">'='</span> + str(v) + <span class="p_string">'\r\n'</span> 
        <span class="p_word">return</span> result

<span class="p_commentline">#--------------------------- Testing --------------------------------------</span>


</PRE><DIV class="commentbox">From RFC4566 p.10<pre>   An example SDP description is:

      v=0
      o=jdoe 2890844526 2890842807 IN IP4 10.47.16.5
      s=SDP Seminar
      i=A Seminar on the session description protocol
      u=http://www.example.com/seminars/sdp.pdf
      e=j.doe@example.com (Jane Doe)
      c=IN IP4 224.2.17.12/127
      t=2873397496 2873404696
      a=recvonly
      m=audio 49170 RTP/AVP 0
      m=video 51372 RTP/AVP 99
      a=rtpmap:99 h263-1998/90000
</pre></DIV><PRE>
<span class="p_word">def</span> testSDP():
    s = <span class="p_triple">'''v=0\r
o=jdoe 2890844526 2890842807 IN IP4 10.47.16.5\r
s=SDP Seminar\r
i=A Seminar on the session description protocol\r
u=<a href="http://www.example.com/seminars/sdp.pdf\r">http://www.example.com/seminars/sdp.pdf\r</a>
e=j.doe@example.com (Jane Doe)\r
c=IN IP4 224.2.17.12/127\r
t=2873397496 2873404696\r
a=recvonly\r
m=audio 49170 RTP/AVP 0\r
m=video 51372 RTP/AVP 99\r
a=rtpmap:99 h263-1998/90000\r
'''</span>
    sdp = SDP(s)
    <span class="p_word">assert</span> str(sdp) == s
    
<span class="p_word">if</span> __name__ == <span class="p_string">'__main__'</span>:
    <span class="p_word">import</span> doctest
    doctest.testmod()
    testSDP()


  </PRE></BODY>
</HTML>
